(function($) {
    $.fn.ajaxForm = function(options) {
        var defaultOptions = {
            onSuccess: null,
            onError: null
        };
        var setting = $.extend(defaultOptions, options);
        this.each(function() {
            var $this = $(this);
            var url = $this.attr('action');
            if ($this.is('form')) {
                $(document).on('submit', $this, function(e) {
                    $this.find('.control-group').removeClass('error');
                    $this.find('.controls > .errormsg').remove();
                    var postData = $this.serialize();
                    $('.dis').attr('disabled', 'disabled');
                    $.post(url,
                            postData,
                            function(response) {
                                $('.cue_span').css({display: 'none'});
                                $("input").css("border", "1px #cccccc solid");

                                //验证码重置
                                if($('.LUOCAPTCHAreset').length>0) {
                                    LUOCAPTCHA.reset();
                                }

                                if (response.code == 'success') {
                                    if (response.data.login) {
                                        document.write(response.data.login);
                                    }
                                    window.confirm = true;
                                    $.messager.popup('操作成功');
                                    if ($this.data('url')) {
                                        H.jump($this.data('url'), function() {
                                            $('.dis').removeAttr('disabled');
                                        });
                                    }

                                    //执行自定义回调函数
                                    if($this.attr('callback') && $this.attr('callback').length > 0) {
                                        var callbackFun = new Function('window', $this.attr('callback'))({});
                                    }

                                } else {
                                    $('.dis').removeAttr('disabled');
                                    if (typeof (response.data) !== 'object') {
                                        if ($("#" + response.data).length > 0) {
                                            $("#" + response.data).css({
                                                "display": "inline",
                                                "color": "#ff4849"
                                            });
                                            $.messager.popup(response.message);
                                            // $("#" + response.data + "_input").focus();
                                            $("#" + response.data + "_input").css("border", "1px #ff4849 solid");
                                            // $("#" + response.data).html(response.message);
                                        }
                                        else {
                                            $.messager.popup(response.message, 'error');
                                        }
                                    }
                                    else {
                                        if(!isEmptyObject(response.data)){
                                            reg.check(response.data);
                                        }else{
                                            $.messager.popup(response.message, 'error');
                                        }
                                    }
                                }
                                
                                if (response.url) {
                                    H.jump(response.url, function() {
                                        $('.dis').removeAttr('disabled');
                                    });
                                }
                            }, 'json'
                            );
                    return false;
                });
            } else if ($this.is('a')) {
                $this[0].addEventListener('tap', function() {
                    confirmMsg = $this.data('confirm');
                    if (confirmMsg) {
                        if (!confirm(confirmMsg)) {
                            return false;
                        }
                    }
                    $.get($this.data('href'), {}, function(response) {
                        if (response.code == 'success') {
                            if (response.data.login) {
                                document.write(response.data.login);
                            }
                            var message = response.message ? response.message : '�����ɹ�';
                            $.messager.popup(message);
                            if (response.url) {
                                H.jump(response.url);
                            }
                        } else {
                            $.messager.popup(response.message, 'error');
                        }
                    }, 'json');
                });
            }
        });
    };
})(jQuery);

$('.ajax').ajaxForm();


var H = {
    HOST: 'http://' + window.location.host,
    Confirm: true
    , jump: function(url, cb) {
        this.Confirm = false;
        jumpto = '';
        if (url.substr(0, 7) == 'http://' || url.substr(0, 8) == 'https://') {
            jumpto = url;
        } else {
            jumpto = this.HOST + '/' +
                    (url.substr(0, 1) == '/' ? url.substr(1) : url);
        }
        window.location.href = jumpto;
        if(cb) {
            return cb;
        }
    }
};

var reg = {
    HOST:   '/order/index/orderid/',
    SEARCH: '/race/check/raceid/',
    DETAIL: '/register/detail/raceid/',
    check: function(data) {        
        var raceid = data.raceid,name=[],payed=[],state=[],ids=[],normal = data.normal,payedid=[],
            reg = data.regs;
        $.each(reg,function(n,value) {
            if(value.order_status !== 'no_order' && value.order_status !== 'payed'){    //expired unpay
                name.push(value.name);
            }else if(value.order_status === 'payed' && (value.state === 'reqaband'||value.state === 'aband'||value.state === 'abanding')){               //payed
                state.push(value.name);
            }else if(value.order_status === 'payed'){               //payed
                payed.push(value.name);
                payedid.push(value.certificate_id);
            }else if(value.order_status === 'no_order'){            //no_order
                ids.push(value.id);   
            }
        });
        var type = $(".form-inline input[name=type]").val(),
            from = $("input[name=from]").val(),
            team_url = '',
            eventid = $("input[name=eventid]").val(),
            raceid = $("input[name=raceid]").val();
        if(type !== 'personal'){
            var teamid = $("input[name=teamid]").val();
            if(teamid){
                team_url = "/teamid/"+teamid;
            }
        }  
        if(!isEmptyObject(name)){
            console.log(type);
            $.messager.popup("【"+name.join()+"】含有未处理的订单，请先处理");
            setTimeout(function () { 
                location.href = "/register/total/raceid/"+ raceid +"/type/"+type;
            }, 3000);
            return false;
        }
        var msg= '';
        if(!isEmptyObject(normal)){
            msg = ',其余人是否继续报名';
        }
        if(!isEmptyObject(state)){
            if (!confirm("下述用户重复报名【"+state.join()+"】"+msg)) {
                return false;
            }
        }
        if(!isEmptyObject(payed)){
            if (!confirm("【"+payed.join()+"】已报名成功"+msg)) {
                return false;
            }
            if(msg===''){
                return false;
            }
            //确认之后，去除选中状态        
            $.each(payedid,function(n,value){
                var checked = $(this).is(':checked');
                $(':checkbox[value="'+value+'"]').prop('checked', checked);
                $(':checkbox[value="'+value+'"]').parents(".checkall-par").removeClass('check-wrap-active');
                $(':checkbox[value="'+value+'"]').parents(".checkall-par").parents('.check-wrap').removeClass('check-border');            
            }); 
            $('form.form-horizontal').append('<input type="hidden" name="reset" value="ignore">');
            $('form.form-horizontal').submit();
            $('form.form-horizontal').find('input[name="reset"]').remove();
            return false;
        }
        //不存在订单删除后再次发起.
        if(!isEmptyObject(ids)){
            var url = "http://interface.ihuipao.cn/register/checkoutBy"+team_url;
            $.ajax({
                type: "POST",url: url,dataType: "json",
                data: {id:ids,
                    normal:normal,
                    type:type,
                    from:from,
                    eventid:eventid,
                    raceid:raceid
                },
                success: function(data){
                    console.log(data);
                    $('form.form-horizontal').append('<input type="hidden" name="reset" value="ignore">');
                    $('form.form-horizontal').submit();
                    $('form.form-horizontal').find('input[name="reset"]').remove();

                 },
                 error:function(){
                     $.messager.popup("网络问题，请稍后再试");
                 }                 
            });
        }
        
        $('.dis').removeAttr('disabled');
    }
};

function isEmptyObject(e) {
    var t;
    for (t in e)
            return !1;
    return !0;
}